from fastapi import APIRouter, Depends
from sqlalchemy.orm import joinedload

from apps.models import SysUser
from apps.system import schemas, cruds
from apps.system.params.user import UserParams
from core.dependencies import IdList
from core.response import SuccessResponse, ErrorResponse
from core.auth import FullAdminAuth, Auth, AllUserAuth

router = APIRouter(prefix="/user")


@router.post("/create", summary="创建用户")
async def create_user(
        data: schemas.UserIn,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.user.create"]))
):
    return SuccessResponse(
        await cruds.UserDal(auth.db).create_data(data=data),
        msg="创建成功"
    )


@router.get("/list", summary="用户列表")
async def list_users(
        params: UserParams = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.user.list"]))
):
    model = SysUser
    options = [joinedload(model.roles), joinedload(model.depts)]
    schema = schemas.UserOut
    datas, count = await cruds.UserDal(auth.db).get_datas(
        **params.dict(),
        v_options=options,
        v_schema=schema,
        v_return_count=True
    )
    return SuccessResponse(datas, count=count)


@router.put("/update/{data_id}", summary="更新用户")
async def update_user(
        data_id: int,
        data: schemas.UserUpdate,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.user.update"]))
):
    return SuccessResponse(
        await cruds.UserDal(auth.db).put_data(data_id, data),
        msg="修改成功"
    )


@router.delete("/delete", summary="删除用户")
async def delete_user(
        ids: IdList = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.user.delete"]))
):
    if auth.user.id in ids.ids:
        return ErrorResponse("不能删除当前登录用户")
    elif 1 in ids.ids:
        return ErrorResponse("不能删除超级管理员用户")
    await cruds.UserDal(auth.db).delete_datas(ids=ids.ids, v_soft=True, is_active=False)
    return SuccessResponse(msg="删除成功")


@router.post("/password/reset/{data_id}", summary="管理员重置用户密码")
async def reset_user_password_manage(
        data_id: int,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.user.reset_password"]))
):
    return SuccessResponse(
        await cruds.UserDal(auth.db).reset_password_by_id(data_id),
        msg="重置用户密码成功"
    )


@router.post("/password/reset", summary="个人重置用户密码")
async def reset_user_password_self(
        data: schemas.ResetPwd,
        auth: Auth = Depends(AllUserAuth())
):
    return SuccessResponse(
        await cruds.UserDal(auth.db).reset_password(auth.user, data),
        msg="重置成功"
    )
